<?php
class User_IndexController extends TIGT_Controller_Action{
    protected $_arrParam;
    protected $_user;
    
    public function init(){
        Zend_Loader::loadClass('InputModel');
    	$this->_arrParam = $this->_request->getParams();   
		
//      Bo di cac truong ko can thiet
		unset($this->_arrParam['module']);
		unset($this->_arrParam['controller']);
		unset($this->_arrParam['action']);
		
//      Them vao view cac chung
		$this->view->controller =  $this->_request->getControllerName();
		$this->view->action =  $this->_request->getActionName();
		$this->view->module = $this->_request->getModuleName();
//      Loc cac bien dau vao
		foreach ($this->_arrParam as &$p){
			$p = InputModel::standardInputString($p);
		}
        
//      lay dia chi host
        $pageURL = 'http';
        if (!empty($_SERVER['HTTPS'])) {
            if ($_SERVER['HTTPS'] == 'on') {
                $pageURL .= "s";
            }
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"];
        }
        $this->_host = $this->view->host = $pageURL;
        
//    	Truyền tham số ra view 
    	$this->view->arrParam = $this->_arrParam;  
    }
    
//      Load cac file css, js, va khoi tao cac bien can thiet
    public function preDisPatch(){
//      Load model
        Zend_Loader::loadClass('AuthModel');
//      Them cac file css va js can thiet

//    	Chọn layout mặc định
    	
		$template_path = TEMPLATE_PATH . "/user/";
		$this->loadTemplate($template_path,'template.ini','template');
        $auth = new AuthModel();
        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity();
            $this->view->user = $this->_user = $user;
        }
    }
    
    public function indexAction(){    
//      Load cac model can thiet   
        
//      Them cac file css va js can thiet
//      Xu ly
        $params = $this->_arrParam;
    }
    
    // Trang dang nhap
    public function loginAction(){
        $this->view->headLink()->appendStylesheet("/css/default/form.css");
        Zend_Loader::loadClass('LightOpenID');
        Zend_Loader::loadClass('AuthModel');
        Zend_Loader::loadClass('UserModel');
		$this->view->headTitle()->set('Đăng nhập');
        $request = $this->getRequest();
		$view = $this->view;
		//    	Chọn layout mặc định
		$template_path = TEMPLATE_PATH . "/user/";
		$this->loadTemplate($template_path,'template.ini','login');
		//check authenticated
		$auth = new AuthModel();
		if($auth->hasIdentity()) $this->_redirect('/user/index');
        $params = $this->_arrParam;   
        // Nhan cac thong diep tu login-exec
        if(!empty($params['login_error'])){
            switch($params['login_error']){
                case 1: $this->view->error_messages = "Không đúng phương thức truyền"; break;
                case 2: $this->view->error_messages = "Chưa nhập tên hoặc mật khẩu"; break;
                case 3: $this->view->error_messages = "Sai tên đăng nhập hoặc mật khẩu"; break;
                default: $this->view->error_messages = "Sai tên đăng nhập hoặc mật khẩu"; break; 
            }
            
        }
		if($request){ 
            try {
    			$openid = new LightOpenID('http://home.tienichgiaothong.vn/');
    			//not login
    			if(!$openid->mode) {      			     
    				if(!empty($params['login']) && !empty($params['type'])) {
    				    if($params['type'] == 1){ // Dang nhap qua google service
				            $openid->identity = 'https://www.google.com/accounts/o8/id';
                            $openid->required = array('namePerson/first', 'namePerson/last', 'contact/email');
                            //$openid->optional = array('namePerson', 'namePerson/friendly');
        					header('Location: ' . $openid->authUrl());    
    				    }else if($params['type'] == 2){ // Dang nhap qua facebook service
    				        $openid->identity = 'http://facebook-openid.appspot.com/';  
                            $openid->required = array('namePerson/first', 'namePerson/last', 'contact/email');
                            //$openid->optional = array('namePerson', 'namePerson/friendly');
                            header('Location: ' . $openid->authUrl());  
    				    }
    				}
    				//user cancel
    			} elseif($openid->mode == 'cancel') {
    				$warning_message = 'User has canceled authentication!';
    				$view->warning_messages = $warning_message;
    			} else {
    				//login success
    				if($openid->validate())
    				{
    				    if($params['type'] == 1){
    				        //gmail tra ve
        					$auth = new AuthModel();
        					$identity = $openid->identity;
        					$attributes = $openid->getAttributes();
        					$email = $attributes['contact/email'];
        					$first_name = $attributes['namePerson/first'];
        					$last_name = $attributes['namePerson/last'];
                            
                            //xu ly
                            $userModel = new UserModel();
                            // Kiem tra xem user da dang ki chua??
                            if($user = $userModel->getAccountByGoogleAccount($email, 0)){ 
                                if($user['status'] == 1){
                                    $auth->setIdentity($identity, $name, $user['idAccount']);    
                                }else{
                                    $view->error_messages = "Tài khoản tạm thời bị cấm";
                                }
                            }else{ // Neu chua, dang ki
                                $account_id = $userModel->insertAccount(array("google_account"=>$email, "create_time"=>date("Y-m-d H:i:s")));
                                $user_id = $userModel->insert(array("FullName"=>$first_name." ".$last_name, "idNormalUser"=>$account_id));
                                $auth->setIdentity($identity, $name, $account_id, GOOGLE_USER);
                            }
        					$this->_redirect("/user/index");
    				    }else{
    				        //facebook tra ve
        					$auth = new AuthModel();
        					$identity = $openid->identity;
                            // Lay thong tin tu facebook
                            $facebook_account = substr($identity, 35); 
                            //xu ly
                            $userModel = new UserModel();
                            // Kiem tra xem user da dang ki chua??
                            if($user = $userModel->getAccountByFacebookAccount($facebook_account, 0)){ 
                                if($user['status'] == 1){
                                    $auth->setIdentity($identity, $facebook_account, $user['idAccount']);    
                                }else{
                                    $view->error_messages = "Tài khoản tạm thời bị cấm";
                                }
                            }else{ // Neu chua, dang ki
                                $account_id = $userModel->insertAccount(array("face_account"=>$facebook_account, "create_time"=>date("Y-m-d H:i:s")));
                                $user_id = $userModel->insert(array("FaceAccount"=>$facebook_account, "idNormalUser"=>$account_id));
                                $auth->setIdentity($identity, $facebook_account, $account_id, FACEBOOK_USER);
                            }
                            $this->_redirect("/user/index");
    				    }
    				}
    				else
    				{
    					$view->error_messages = $message;
    				}
    			}
    		} catch(Exception $e) {
    			$message = $e->getMessage();
    			$view->error_messages = $message;
    		}
        }
    }
    
    public function loginExecAction(){
        Zend_Loader::loadClass('AuthModel');
        Zend_Loader::loadClass('UserModel');
        $params = $this->_arrParam;
        try{
            
            if($this->_request->isPost()){                
                //xu ly
                $userModel = new UserModel();
                $auth = new AuthModel();
                if(!empty($params['UserName']) && !empty($params['Password'])){
                    if($user = $userModel->checkAccount($params['UserName'], $params['Password'])){
                        $auth->setIdentity($user['idAccount'], $user['UserName'], $user['idAccount'], NORMAL_USER);
                        $this->_redirect("/user/index");
                    }else{
                        $this->_redirect("/user/index/login?login_error=3");    
                    }     
                }else{
                    $this->_redirect("/user/index/login?login_error=2");
                }   
            }else{
                $this->_redirect("/user/index/login?login_error=1");
            }       
        }catch(Exception $e){
            echo $e->getMessage();die;
        } 
    }
    
    public function logoutAction(){
        Zend_Loader::loadClass('AuthModel');
        $auth = new AuthModel();
        $auth->clearIdentity();
        $this->_redirect('/index');
    }
}